<!--
 * @Author: baron
 * @Date: 2024-11-27 14:27:19
 * @LastEditors: baron
 * @LastEditTime: 2025-04-18 11:03:12
 * @Description: 行业资讯
 * @功能: 
-->

<template>
    <view class="news-container">
        <!-- 顶部导航栏 -->
        <uni-nav-bar left-icon="left" title="行业资讯" @clickLeft="goBack" fixed status-bar right-icon="search"
            @clickRight="onSearch" :border="false" background-color="#ffffff"></uni-nav-bar>

        <!-- 分类标签栏 -->
        <view class="category-tabs">
            <scroll-view scroll-x class="tabs-scroll" show-scrollbar="false">
                <view class="tab-item" v-for="(item, index) in categories" :key="index"
                    :class="{ active: currentCategory == item.dictValue }" @tap="switchCategory(item.dictValue)">
                    {{ item.dictLabel }}
                </view>
            </scroll-view>
            <view class="tab-line"></view>
        </view>

        <!-- 资讯列表 -->
        <view class="content">
            <scroll-view scroll-y class="news-list" @scrolltolower="loadMore" refresher-enabled
                @refresherrefresh="onRefresh" :refresher-triggered="isRefreshing">
                <view class="news-item" v-for="(item, index) in newsList" :key="item.id" @tap="goToDetail(item)">
                    <view class="news-tag">{{ item.categoryName }}</view>
                    <view class="news-title">{{ item.title }}</view>
                    <view class="news-remark">{{ item.remark }}</view>
                    <view class="news-meta">
                        <text class="author" v-if="item.author">{{ item.author }}</text>
                        <text class="date">{{ item.releaseTime | formatDate }}</text>
                        <text class="views">浏览 {{ item.viewCount }}</text>
                    </view>
                    <image v-if="item.coverImage" :src="item.coverImage" mode="aspectFit" class="news-image"></image>
                </view>

                <!-- 底部加载状态 -->
                <view class="loading-more" v-if="loading && !noMore">
                    <view style="color:#999;">正在加载...</view>
                </view>
                <view class="no-more" v-if="noMore && newsList.length > 0">
                    <view style="color:#999;">没有更多了~</view>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script>
import { hasLogin } from '@/utils/login';
import { getNewsList } from '@/api/news'; // Import API
import { getDictType } from '@/api/common'; // Import API
import dayjs from 'dayjs'; // Import dayjs for formatting

export default {
    data() {
        return {
            currentCategory: '',
            isRefreshing: false,
            hasMore: true,
            categories: [
                // { id: '1', name: '全部' },
                // { id: '2', name: '行业动态' },
                // { id: '3', name: '政策法规' },
                // { id: '4', name: '技术趋势' },
                // { id: '5', name: '应用案例' }
            ],
            newsList: [],
            page: 1,
            pageSize: 10,
            total: 0,
            loading: false,
            noMore: false
        }
    },
    filters: { // Add filter for date formatting
        formatDate(value) {
            if (!value) return '';
            // Assuming releaseTime is in 'YYYY-MM-DD HH:mm:ss' format, display only date part
            return dayjs(value).format('YYYY-MM-DD');
        }
    },
    async onLoad() {
        try {
            await hasLogin();
            await this.getDictType();
            await this.getNewsList()
        } catch (error) {
            console.log('error---', error);
        }
    },
    methods: {
        goBack() {
            uni.navigateBack()
        },
        onSearch() {
            uni.showToast({
                title: '搜索功能开发中',
                icon: 'none'
            })
        },
        switchCategory(categoryId) {
            this.currentCategory = categoryId
            this.page = 1
            this.newsList = []
            this.noMore = false
            this.getNewsList()
        },
        async getDictType() {
            try {

                const { data } = await getDictType('news_category');
                this.categories = [{ dictValue: '', dictLabel: '全部' }, ...data];
            } catch (error) {

            }
        },
        async getNewsList() {
            if (this.loading || this.noMore) return
            this.loading = true
            this.isRefreshing = this.page === 1; // Set refreshing state
            try {
                const params = {
                    // category: this.currentCategory === 'all' ? undefined : this.currentCategory, // Adjust based on API needs
                    pageNum: this.page,
                    pageSize: this.pageSize
                };
                // If currentCategory is not 'all', add it to params
                if (this.currentCategory !== 'all') {
                    params.categoryId = this.currentCategory; // Assuming API expects categoryId
                }

                const { rows, total } = await getNewsList(params);

                const formattedRows = rows.map(item => ({
                    ...item,
                    // Add any necessary client-side formatting/mapping here if needed
                    // Example: Set tagColor based on categoryName (if required)
                    tagColor: this.getTagColor(item.categoryName)
                }));

                if (this.page === 1) {
                    this.newsList = formattedRows;
                } else {
                    this.newsList = [...this.newsList, ...formattedRows];
                }
                this.total = total;

                this.noMore = this.newsList.length >= this.total;
                if (!this.noMore) {
                    this.page++;
                }
            } catch (error) {
                console.error("获取资讯列表失败:", error);
                uni.showToast({
                    title: '获取资讯失败',
                    icon: 'none'
                })
            } finally {
                this.loading = false;
                this.isRefreshing = false; // End refreshing state
            }
        },
        loadMore() {
            console.log('loadMore-------')
            this.getNewsList()
        },
        onRefresh() {
            this.page = 1
            this.newsList = []
            this.noMore = false
            this.loading = false; // Reset loading flag
            this.getNewsList()
        },
        goToDetail(item) {
            uni.navigateTo({
                url: `/pages/news/detail?id=${item.id}`
            })
        },
        // Helper function to get tag color (example)
        getTagColor(categoryName) {
            switch (categoryName) {
                case '行业动态': return '#007AFF';
                case '政策法规': return '#11D183';
                case '技术趋势': return '#FF6B00';
                case '技术前沿': return '#FF6B00'; // Added based on example data
                default: return '#666';
            }
        }
    }
}
</script>

<style lang="scss">
.news-container {
    min-height: 100vh;
    background-color: #f5f5f5;

    .category-tabs {
        position: fixed;
        top: var(--window-top);
        left: 0;
        right: 0;
        background-color: #fff;
        z-index: 99;

        .tabs-scroll {
            white-space: nowrap;
            height: 88rpx;
            width: 100%;

            &::-webkit-scrollbar {
                display: none;
            }
        }

        .tab-item {
            display: inline-block;
            padding: 0 32rpx;
            height: 88rpx;
            line-height: 88rpx;
            font-size: 28rpx;
            color: #666;
            position: relative;

            &.active {
                color: #007AFF;
                font-weight: 500;

                &::after {
                    content: '';
                    position: absolute;
                    bottom: 0;
                    left: 50%;
                    transform: translateX(-50%);
                    width: 32rpx;
                    height: 4rpx;
                    background-color: #007AFF;
                    border-radius: 2rpx;
                }
            }
        }

        .tab-line {
            height: 1rpx;
            background-color: #eee;
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
        }
    }

    .content {
        height: 92vh;
        overflow: auto;
        width: calc(100% - 40rpx);
        margin: 20rpx;
        margin-top: 100rpx;
    }

    .news-list {
        position: relative;
        height: 100%;
        width: 100%;

        .news-item {
            background-color: #fff;
            border-radius: 12rpx;
            padding: 24rpx;
            margin-bottom: 20rpx;

            .news-tag {
                display: inline-block;
                font-size: 24rpx;
                margin-bottom: 16rpx;
                color: #24bdff;
                background-color: #e1f8fe;
                border-radius: 8rpx;
                padding: 4rpx 12rpx;
            }

            .news-title {
                font-size: 32rpx;
                color: #333;
                font-weight: 500;
                line-height: 1.4;
                margin-bottom: 8rpx;
            }

            .news-remark {
                font-size: 26rpx;
                color: #666;
                line-height: 1.5;
                margin-bottom: 16rpx;
                display: -webkit-box;
                -webkit-box-orient: vertical;
                -webkit-line-clamp: 2;
                overflow: hidden;
                text-overflow: ellipsis;
            }

            .news-meta {
                display: flex;
                align-items: center;
                font-size: 24rpx;
                color: #999;
                margin-bottom: 16rpx;

                .author {
                    margin-right: 20rpx;
                }

                .date {
                    margin-right: 20rpx;
                }
            }

            .news-image {
                width: 100%;
                height: 320rpx;
                border-radius: 8rpx;
                margin-top: 16rpx;
                background-color: #eee;
            }
        }
    }

    .loading-more,
    .no-more {
        text-align: center;
        padding: 20rpx 0;
    }
}
</style>